package com.efast.cafe.commponent.statemach.service.impl;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.efast.cafe.commponent.statemach.base.HandleBaseProcessorService;
import com.efast.cafe.commponent.statemach.bean.TaskParamBean;
import com.efast.cafe.commponent.statemach.constant.StatemachConstant;
import com.efast.cafe.commponent.statemach.service.IStateMachService;
import com.efast.cafe.commponent.statemach.service.IStatemMachCoreService;
import com.efast.cafe.framework.spring.SpringContextUtils;
import com.efast.cafe.util.StringUtil;
import com.efast.cafe.util.date.DateUtils;


@Service
public class StatemMachCoreServiceImpl implements IStatemMachCoreService {

	@Autowired
	private IStateMachService stateMachService; 
	
	@Override
	public void executeStateMach(TaskParamBean taskParam,String htype)throws Exception {
		JSONObject json = JSON.parseObject(taskParam.getParajson());
		JSONObject extFormData = json.getJSONObject("extFormData");
		Set<String> extformEntitySet = extFormData.keySet();
    	boolean isHandle = false;
    	//保存entity为handler数据流
    	Map<String, JSONObject> extFormDataJson = new HashMap<>();
    	extformEntitySet.forEach(k->{
    		extFormDataJson.put(k, JSON.parseObject(extFormData.get(k).toString()));
    	});
    	for(String ext : extformEntitySet){//所有扩展实体
    		String key  = taskParam.getConfId()+htype+ext;
    		String handleClassName = StatemachConstant.getHandleClass(key);
	        if(StringUtil.isNotBlank(handleClassName)){
	        	//调用扩展的状态机handler 处理entity
	        	Object t = processEntity(handleClassName,ext,extFormData,json,extFormDataJson);
	        	json.getJSONObject("extFormData").put(ext, t);
	        	isHandle = true;
	        }
    	}
    	if(isHandle){//存在扩展handler 将数据重新包装
    		taskParam.setParajson(JSON.toJSONStringWithDateFormat(json, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
    	}
    	//调用状态机服务 执行主流程以及处理流程配置的主表单数据
    	stateMachService.execute(taskParam.getConfId(), taskParam.getTaskId(), taskParam.getParajson(),extFormDataJson);
    	
    	//额外的扩展实体 不走状态机 走自定义处理业务类
    	JSONObject extraFormData = json.getJSONObject("extraFormData");
    	if(null!=extraFormData){
    		Set<String>extraformEntitySet = extraFormData.keySet();
        	for(String extra : extraformEntitySet){//所有扩展实体
        		String key  = taskParam.getConfId()+htype+extra;
        		String handleClassName = StatemachConstant.getHandleClass(key);
    	        if(StringUtil.isNotBlank(handleClassName)){
    	        	processEntity(handleClassName,extra,extraFormData,json,extFormDataJson);
    	        }
        	}
    	}
    	
    	
	}
	
	
	/**
	 * 调用扩展handler 处理entity
	 * @param handleClassName
	 * @param ext
	 * @param extFormData
	 * @param taskParamjson
	 * @param extFormDataJson
	 * @return
	 * @throws ClassNotFoundException
	 */
	private Object processEntity(String handleClassName,String ext,JSONObject extFormData,
			JSONObject taskParamjson,Map<String, JSONObject> extFormDataJson)throws Exception{
		Class<?> interfaceClazz = Class.forName(handleClassName);
    	ParameterizedType type = (ParameterizedType)interfaceClazz.getGenericInterfaces()[0];
    	Class<?> entityClass = (Class<?>)type.getActualTypeArguments()[0];
		@SuppressWarnings("unchecked")
		HandleBaseProcessorService<Object> processService = 
    			(HandleBaseProcessorService<Object>) SpringContextUtils.getBean(interfaceClazz);
    	Object t = extFormData.getObject(ext,entityClass);
    	processService.process(taskParamjson, t,extFormDataJson);
    	return t;
	}

}
